package tfsIssueTracker;

import jetbrains.buildServer.issueTracker.AbstractIssueFetcher;
import jetbrains.buildServer.issueTracker.IssueData;
import jetbrains.buildServer.util.cache.EhCacheUtil;
import org.apache.commons.httpclient.Credentials;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import tfsIssueTracker.commands.GetIssueByIdCommand;

public class TfsIssueFetcher extends AbstractIssueFetcher {
    private final TfsExeWrapper wrapper;

    public TfsIssueFetcher(@NotNull EhCacheUtil cacheUtil, TfsExeWrapper wrapper) {
        super(cacheUtil);
        this.wrapper = wrapper;
    }

    @NotNull
    public IssueData getIssue(@NotNull String host, @NotNull String id, @Nullable Credentials credentials) throws Exception {
        final String myHost = host;
        final String myId = id;
        final Credentials myCredentials = credentials; 

        return getFromCacheOrFetch(getUrl(host, id), new FetchFunction(){
            @NotNull
            public IssueData fetch() throws Exception {
                return new GetIssueByIdCommand(myId, Settings.create(myHost, myCredentials, wrapper)).execute();
            }
        });
    }

    @NotNull
    public String getUrl(@NotNull String host, @NotNull String id) {
        // this is not actually the url of the issue, but nonetheless this method seems unused except for creating the cache key
        return appendTrailingSlash(host) + id;
    }

    private String appendTrailingSlash(String host) {
        if(host.endsWith("/"))
            return host;

        return host + "/";
    }
}
